import '../../css/cntMenu.css';
import __DB__               from '../db/index.js';
import __tool__             from '../tool/index.js';
import __canvas__           from '../canvas/index.js';
import __customEvent__      from '../customEvent/index.js';

class cntMenuClass{
    constructor(){
        this.x = 0;         // 菜单出现的坐标X
        this.y = 0;         // 菜单出现的坐标Y
        this.items = [];    // 一级菜单项
        this.type = '';     // 菜单类型（canvas,node,line）
        this.lists = {      // 菜单测试项
            // canvas:[
            //     {label:"测试",id:"test",name:"canvas",icon:"",line:"down"},
            //     {label:"测试",id:"test3",name:"canvas",icon:""},
            //     {label:"测试2",id:"test1",name:"canvas",icon:"",line:"up",children:[
            //         {label:"1",id:"a1",name:"canvas",icon:"",pid:"test1",line:"down"},
            //         {label:"2",id:"a2",name:"canvas",icon:"",pid:"test1"},
            //         {label:"3",id:"a3",name:"canvas",icon:"",pid:"test1"},
            //         {label:"4",id:"a4",name:"canvas",icon:"",pid:"test1",line:"up"},
            //     ]},
            // ]
        };

        this.nodeId = null;// 菜单所属节点ID
        this.twoMenuId = null; // 二级菜单所属Id
        this.isClear = true;// 是否可清空右键菜单
    }

    initList(res={}){
        let type    = res.type,
            items   = res.items;

        if(!type || !items)return;

        this.lists[type] = items;
    }

    // 初始化
    init(res){
        this.x      = res.x;
        this.y      = res.y;
        this.type   = res.type;
        this.items  = this.lists[res.type];

        if(res.type === "node"){
            this.nodeId = res.data.id;
        }

        this.clear();// 清除
        this.creat();// 创建右键菜单
    }

    // 创建右键菜单
    creat(){
        let cntEl = document.createElement('div');
        cntEl.setAttribute('id','cntMenu');
        cntEl.setAttribute('class','xmd-contentMenu');
        let cls = __DB__.publicData.style.contextMenu.class;
        cls&&cntEl.classList.add(cls);

        cntEl.oncontextmenu = e=>{
            e.stopPropagation();
            e.preventDefault();
        }
        
        // 创建菜单项
        let iEls = this.creatItems();
        if(!iEls || iEls.length === 0)return;
        iEls.forEach(el=>{
            cntEl.appendChild(el);
        })

        // 添加至body
        document.body.append(cntEl);
        document.onclick = ()=>{
            // document.onclick = null;
            if(this.isClear)this.clear();
        };

        cntEl.onmouseout = e=>{
            this.isClear = true;// 是否可清空右键菜单

            let cntItemEls = document.querySelectorAll('.xmd-cntItem');
            cntItemEls.forEach(el=>{
                el.classList.remove('xmd-cntItem-hover')
            });

            document.onclick = ()=>{
                document.onclick = null;
                if(this.isClear)this.clear();
            };
        };

        // 重置右键出现的位置
        cntEl.style.cssText = `
            top             : ${this.y}px;
            left            : ${this.x}px;
        `;

        // 右键菜单位置自适应
        let win_w = __canvas__.main.getBoundingClientRect().width;
        let win_h = __canvas__.main.getBoundingClientRect().height;
        let box_w = cntEl.getBoundingClientRect().width;
        let box_h = cntEl.getBoundingClientRect().height;

        if(this.x + box_w >=  win_w){
            let xx = this.x - box_w;
            cntEl.style.left = xx + "px";
            this.x = xx;
        }

        if(this.y + box_h >=  win_h){
            let yy = this.y - box_h;
            cntEl.style.top = yy + "px";
            this.y = yy;
        }
    }

    // 创建菜单项
    creatItems(){
        let items = this.items;
        if(!items)return;
        if(items.length === 0)return;
        let htmlEl = [];

        items.forEach(el=>{
            let iEl = document.createElement('div');
            iEl.setAttribute('class','xmd-cntItem');
            iEl.setAttribute('id',el.id);
            iEl.setAttribute('name',el.name);
            iEl.innerHTML = el.label;

            if(el.line){
                if(el.line === "down"){
                    iEl.classList.add('xmd-cntItem-lineDown')
                }
                else if(el.line === "up"){
                    iEl.classList.add('xmd-cntItem-lineUp')
                }
            }

            if(el.icon)iEl.classList.add(el.icon);

            // 二级菜单
            let twoEl = [];
            if(el.children && el.children.length > 0){
                iEl.classList.add('xmd-cntItem-arrow')
                twoEl = two.call(this,el.children);// 生成二级菜单
            }
  
            htmlEl.push(iEl);

            // 点击选项
            iEl.onclick = (e)=>{
                if(el.children && el.children.length > 0)return;
                let id   = iEl.getAttribute('id');
                let name = iEl.getAttribute('name');
                let data = this.lists[name];

                data = data.filter(item=>{
                    return item.id === id;
                });
                data = data[0];
                this.evt({id,name,el});// 事件处理
                this.clear();// 清除
            }

            // 经过选项
            iEl.onmouseover = e=>{
                this.isClear = true;// 是否可清空右键菜单
                let cntItemEls = document.querySelectorAll('.xmd-cntItem');
                cntItemEls.forEach(el=>{
                    el.classList.remove('xmd-cntItem-hover')
                });
                iEl.classList.add('xmd-cntItem-hover')

                if(this.twoMenuId === el.id)return;
                this.twoMenuId = null;

                // 清除二级菜单
                let conMenuTwoEl = document.getElementById('conMenuTwo');
                if(conMenuTwoEl)document.body.removeChild(conMenuTwoEl);

                // 如果没有二级就不执行后续
                if(twoEl.length === 0)return;
                
                this.twoMenuId = el.id;
                // 生成二级菜单的元素
                let twoMain = document.createElement('div');
                twoMain.setAttribute('id','conMenuTwo');
                twoMain.setAttribute('class','xmd-conMenuTwoMain');

                // 获取当前一级菜单的宽高
                let cntMenuItemEl   = document.getElementById(el.id);
                let tWidth          = cntMenuItemEl.getBoundingClientRect().width;
                let tHeight         = cntMenuItemEl.getBoundingClientRect().height;
                    tWidth          = parseInt(tWidth);
                    tHeight         = parseInt(tHeight);
            
            
                // 计算出二级菜单需要的坐标
                let x = this.x + tWidth + 5;
                let y = this.y + cntMenuItemEl.offsetTop;

                twoMain.style.cssText = `
                    top             : ${y}px;
                    left            : ${x}px;
                    opacity         : 0;
                `;

                twoEl.forEach(ee=>{
                    twoMain.appendChild(ee);
                })
                document.body.append(twoMain);
                this.isClear = false;// 是否可清空右键菜单

                setTimeout(()=>{
                    // 右键菜单位置自适应
                    let win_w = __canvas__.main.getBoundingClientRect().width;
                    let win_h = __canvas__.main.getBoundingClientRect().height;

                    let box_w = twoMain.getBoundingClientRect().width;
                    let box_h = twoMain.getBoundingClientRect().height;
                    
                    if(x + box_w >=  win_w){
                        let xx = x - box_w - tWidth - 10;
                        twoMain.style.left = xx + "px";
                        x = xx;
                    }
            
                    if(y + box_h >=  win_h){
                        let yy = y - box_h + tHeight;
                        twoMain.style.top = yy + "px";
                        y = yy;
                    }

                    twoMain.style.opacity = 1;
                })
                

            }

        });

        return htmlEl;

        // 生成二级菜单
        function two(twos){
            let twoEl = [];
            twos.forEach(el=>{
                let cEl = document.createElement('div');
                cEl.setAttribute('id',el.id);
                cEl.setAttribute('class','xmd-cntItem-two');
                cEl.setAttribute('name',el.name);
                cEl.innerHTML = el.label;

                if(el.line){
                    if(el.line === "down"){
                        cEl.classList.add('xmd-cntItem-lineDown')
                    }
                    else if(el.line === "up"){
                        cEl.classList.add('xmd-cntItem-lineUp')
                    }
                }

                cEl.oncontextmenu = e=>{
                    e.stopPropagation();
                    e.preventDefault();
                }

                cEl.onclick = e=>{
                    let id      = cEl.getAttribute('id');
                    let name    = cEl.getAttribute('name');
                    let label   = cEl.innerHTML;
                    let data    = el;
                    data = data[0];
                    this.evt({id,name,label,data:el});// 事件处理
                }
                
                // 经过选项
                cEl.onmouseover = e=>{
                    this.isClear = true;// 是否可清空右键菜单
                    let cElEls = document.querySelectorAll('.xmd-cntItem-two');
                    cElEls.forEach(el=>{
                        el.classList.remove('xmd-cntItem-hover')
                    });
                    cEl.classList.add('xmd-cntItem-hover')
                };

                cEl.onmouseout = e=>{
                    let cElEls = document.querySelectorAll('.xmd-cntItem-two');
                    cElEls.forEach(el=>{
                        el.classList.remove('xmd-cntItem-hover')
                    });
                }
                
                twoEl.push(cEl);
            });

            return twoEl;
        }
    }

    // 事件处理
    evt(res){
        let id      = res.id,
            name    = res.name,
            label   = res.label,
            data    = res;

        if(name === "node"){
            data = __DB__.get(this.nodeId)            
        }

        // 获取右键所有项，包括二级
        let allItems = [];
        this.items.forEach(el=>{
            if(el.fn)allItems.push(el);
            if(el.children && el.children.length > 0){
                el.children.forEach(el_c=>{
                    if(el_c.fn)allItems.push(el_c);
                })
            }
        })

        for(let el of allItems){
            if(el.id === id){
                el.fn({id,label,name,data,el})
            }
        }
    }

    // 清除
    clear(){
        let cntEl = document.getElementById('cntMenu');
        if(cntEl)document.body.removeChild(cntEl);

        let conMenuTwoEl = document.getElementById('conMenuTwo');
        if(conMenuTwoEl)document.body.removeChild(conMenuTwoEl);
    }
}

let cntMenu = new cntMenuClass();
export default cntMenu;